package com.dhl.rabbitmq.three;

import com.dhl.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 消费者端(测试消息手动应答,消息不丢失，重新放回消息队列)
 * @title: Work2
 * @Author danghailiang
 * @Date: 2022/6/10 9:00
 * @Version 1.0
 */
public class Work2 {

    /**
     * 队列名称
     */
    public static final String TASK_QUEUE_NAME = "ask_name";

    public static void main(String[] args) throws Exception {
        // 获取信道
        Channel channel = RabbitUtils.getChannel();
        // 说明
        System.out.println("C1等待消息处理，处理时间较短");
        // 消息被成功消费时的回调
        DeliverCallback deliverCallback = (String consumerTag, Delivery message) ->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接收到的消息" + new String(message.getBody(), StandardCharsets.UTF_8)) ;
            /**
             * 手动应答
             * 1. deliveryTag:消息的标记 tag
             * 2. multiple:是否批量应答，false,不批量应答，  true：批量
             */
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        /**
         *  0：公平分发(默认值)
         *  1：设置不公平分发
         *  2：预取值
         */
        channel.basicQos(4);
        // 采用手动应答
        boolean autoAck = false;
        channel.basicConsume(
                TASK_QUEUE_NAME,
                autoAck,
                deliverCallback,
                // 消息消费被中断的回调
                consumerTag -> System.out.println(consumerTag + "消费者取消或者中断消费接口回调逻辑")

        );
    }



}
